package com.test.controller;

import com.test.entity.User;
import com.test.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param user  注册用户信息
     * @return
     */
    @RequestMapping("/registry")
    public String userRegistry(User user) {
        try {
            userService.userRegistry(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/registry.jsp";
    }


    /**
     * 用户退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    /**
     * 用户登录
     * @param username  用户名
     * @param password  密码
     * @return
     */
    @RequestMapping("/login")
    public String login(String username, String password) {
        //因为在config中已经配置了SecurityManager,并且也在ShiroFilter中配置了安全管理器,所以在此处可以直接使用SecurityUtiles工具类
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            //基于登录的用户名和面生成token进行校验
            subject.login(new UsernamePasswordToken(username, password));
            //查看认证结果  在自定义的realm中间进行认证校验
            boolean authenticated = subject.isAuthenticated();
            System.out.println("认证成功!");
            return "redirect:/index.jsp";

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误!");
        }
        return "redirect:/login.jsp";
    }
}
